<template>
  <a-transfer
  :dataSource="mDataSource"
  @change="handleChange"
  :render="handleRender"
  @selectChange="handleSelectChange"
  v-model:selected-keys="mValue.selectedKeys"
  v-model:target-keys="mValue.targetKeys">
    <template v-for="item in slotKeys.filter(key=>props[key])" #[item]="slotProps">
      <component :is="renderSlot(props,item,slotProps || {})"/>
    </template>
  </a-transfer>
</template>
<script setup lang="ts">
import { PropType, VNode, onMounted, reactive, ref, watch } from 'vue';
import { renderSlot, requestData } from '../index'
const slotKeys = ['children','footer']
const emits = defineEmits(['update:modelValue','change','selectChange'])
const props = defineProps({
  value: {
    type: Object as PropType<{targetKeys:Array<string>,selectedKeys:Array<string>}>,
    default() {
      return {
        targetKeys: [],
        selectedKeys: []
      }
    }
  },
  children: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  footer: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  render: {
    type: [Object, Function] as PropType<VNode |((item: any)=>VNode | String)>
  },
  api: { // 接口地址或接口函数--->新增属性
    type: [Function, String] as PropType<((param: any)=>Promise<any>) | String>
  },
  dataSource: {
    type: Array as PropType<Array<{
      key: string,
      title: string,
      description?: string,
      disabled?: boolean
    }>>,
    default() {
      return []
    }
  },
  params: {
    type: Object,
    default(){
      return {}
    }
  }
})
const mValue = reactive(props.value)
watch(()=>props.value,()=>{
  mValue.targetKeys = props.value.targetKeys || []
  mValue.selectedKeys = props.value.selectedKeys || []
},{
  deep: true
})
const mDataSource = ref(props.dataSource || [])
watch(()=>props.dataSource,()=>{
  mDataSource.value = props.dataSource as any
},{
  deep: true
})
const handleChange = (targetKeys: any, direction: any, moveKeys: any) => {
  emits('update:modelValue',mValue)
  emits('change',targetKeys,direction,moveKeys)
}
const handleSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) =>{
  emits('update:modelValue',mValue)
  emits('selectChange',sourceSelectedKeys,targetSelectedKeys)
}
const handleRender = (item: any) => {
  if(props.render && typeof props.render == 'function') {
    return props.render(item)
  }
  return item.title
}
onMounted(()=>{
  requestData(props.api,props.params).then(res=>{
    mDataSource.value = res.data || res
  })
})
</script>
<style lang="less" scoped>

</style>